package scope;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;
import org.springframework.core.NamedThreadLocal;

import java.util.HashMap;
import java.util.Map;

/**
 * @author jackcfan
 * @date 2021/9/25
 */
public class ThreadLocalScope implements Scope {
    public static final String SCOPE_NAME = "thread-local";

    private final NamedThreadLocal<Map<String, Object>> threadLocal = new NamedThreadLocal("thread-local-scope"){
        @Override
        protected Object initialValue() {
            return new HashMap<>();
        }
    };

    private Map<String, Object> getContext(){
        return threadLocal.get();
    }

    @Override
    public Object get(String name, ObjectFactory<?> objectFactory) {
        Map<String, Object> context = getContext();
        Object object = context.get(name);
        if(object == null){
            object = objectFactory.getObject();
            context.put(name, object);
        }
        return object;
    }

    @Override
    public Object remove(String name) {
        return getContext().remove(name);
    }

    // 注册销毁回调函数
    @Override
    public void registerDestructionCallback(String name, Runnable callback) {

    }

    // 通过 key 取上下文对象
    @Override
    public Object resolveContextualObject(String key) {
        return getContext().get(key);
    }

    // 会话 id
    @Override
    public String getConversationId() {
        return String.valueOf(Thread.currentThread().getId());
    }
}
